<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\api\controller\Project\Order;
use app\BaseController;
use think\facade\View;
use app\common\model\Admin as AdminModel;
use app\common\model\Order\Order as OrderModel;
use app\common\model\Post\Comment as CommentModel;
use app\common\model\Project\Order as PrOrderModel;
use app\common\model\User\User as UserModel;

class Index extends BaseController
{
    protected $middleware = [
        // except => 设置哪个方法不走中间件
        \app\admin\middleware\LoginAuth::class => ['except' => ['login']],
    ];

    public function index()
    {
        $menu = [
            'name' => '后台首页',
            'title' => '首页'
        ];
        // 订单总收入
        $Revenue = OrderModel::sum('total');
        // 用户总数
        $UserTotal = UserModel::count();
        // 订单总量
        $OrderTotal = OrderModel::count('*');
        // 评论数
        $CommentTotal = CommentModel::count('*');
        // 预约项目
        $num = 10;
        $PrOrderList=PrOrderModel::with(['project','user'])->order('createtime', 'desc')->paginate(['list_rows' => $num, 'query' => request()->param()]);
        // 当前页
        $page = $PrOrderList->currentPage();
        if ($this->request->isAjax()) {
            $action=$this->request->param('action');
            // 本周注册用户
            if ($action=='register') {
                // 获取近七天日期
                $week=get_week();
                $register = [];
                foreach ($week as $key => $item) {
                    $register[]=UserModel::withTrashed()->whereDay('createtime',$item)->count();
                }
                //组装数据
                $data = [
                    'register' => $register,
                ];
                $this->success('返回交易数据成功', null, $data);
            }
            // 近七天历史交易
            if ($action=='business') {
                // 获取近七天日期
                $days=get_weeks();
                $business = [];
                foreach ($days as $key => $item) {
                    $business[]=OrderModel::whereDay('createtime',$item)->sum('total');
                }
                //组装数据
                $data = [
                    'days'=> $days,
                    'business' => $business,
                ];
                $this->success('返回交易数据成功', null, $data);
            }
        }
        return view('', [
            'menu' => $menu,
            'Revenue' => $Revenue,
            'UserTotal' => $UserTotal,
            'OrderTotal' => $OrderTotal,
            'CommentTotal' => $CommentTotal,
            'PrOrderList'=>$PrOrderList,
            'num'=>$num,
            'page'=>$page
        ]);
    }
    // 登录
    public function login()
    {
        // 判断是否已经登录
        $LoginAdmin = !empty(cookie('LoginAdmin')) ? json_decode(cookie('LoginAdmin'), true) : [];

        if ($LoginAdmin) {
            $Adminid = isset($LoginAdmin['id']) ? $LoginAdmin['id'] : 0;

            $Admin = AdminModel::find($Adminid);

            if (!$Admin) {
                cookie('LoginAdmin', null);

                $this->error('非法登录', (string)url('admin/index/login'));
            }

            if ($Admin['state'] != 1) {
                $this->error('该用户被禁用,请重新换账号登录', (string)url('admin/index/login'));
            }

            $this->success('您已登录,无须重复登录', (string)url('admin/index/index'));
        }
        if ($this->request->isPost()) {
            $param = $this->request->param();

            if (!captcha_check($param['captcha'])) {
                $this->error('验证码错误,请重新输入');
            }

            $Admin = AdminModel::where(['username' => $param['username']])->find();

            if (!$Admin) {
                $this->error('用户不存在，请重新输入');
            }
            if ($Admin['password'] != md5($param['password'] . $Admin['salt'])) {
                $this->error('密码错误，请重新输入');
            }
            if ($Admin['state'] != 1) {
                $this->error('该用户被禁用,请重新换账号登录');
            }
            // 封装cookie数组
            $data = [
                'id' => $Admin['id'],
                'username' => $Admin['username'],
                'nickname' => $Admin['nickname'],
                'state' => $Admin['state']
            ];
            // 数组转为json字符串
            $json = json_encode($data);
            // cookie 助手函数
            cookie('LoginAdmin', $json);

            $this->success('登录成功', (string)url('/admin/index/index'));
        }
        // login页面暂停使用模板布局
        View::config(['layout_on' => false]);
        return View::fetch();
    }
    // 退出账号
    public function logout()
    {
        cookie('LoginAdmin', null);

        $this->success('退出成功', (string)url('admin/index/login'));
    }
}
